﻿using Autodesk.Windows;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Linq;
using System.Reflection;


namespace AcadRibbon.Ribbons.Json;
/// <summary>
/// 按钮转换
/// </summary>
internal class RibbonItemConverter : JsonConverter<RibbonItem> {
    public override RibbonItem? ReadJson(JsonReader reader, Type objectType, RibbonItem? existingValue, bool hasExistingValue, JsonSerializer serializer) {
        var jObj = JObject.Load(reader);
        if (jObj.TryGetValue(RibbonItem.TagPropertyName, out var name)) {
            Type type = Assembly.GetAssembly(typeof(RibbonItem)).GetType($"Autodesk.Windows.{name}");
            RibbonItem rbItem = (RibbonItem)System.Activator.CreateInstance(type);
            //写入对象信息s
            serializer.Populate(jObj.CreateReader(), rbItem);

            var propertyInfos = type.GetProperties().Where(it => it.PropertyType == typeof(object));
            foreach (var propertyInfo in propertyInfos) {
                if (jObj.TryGetValue(propertyInfo.Name, out var value)) {
                    if (value.Type == JTokenType.String)
                        propertyInfo.SetValue(rbItem, value.ToString(), null);
                }
            }
            return rbItem;
        }
        return new RibbonButton();
    }

    public override void WriteJson(JsonWriter writer, RibbonItem? value, JsonSerializer serializer) {
        throw new NotImplementedException();
    }
}
